package com.lamer.console.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lamer.console.base.entity.UserRoleRelation;
import com.lamer.console.base.mapper.UserRoleRelationMapper;
import com.lamer.console.base.service.IUserRoleRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 黄诗鹏
 * @since 2021-11-09
 */
@Service
public class UserRoleRelationServiceImpl extends ServiceImpl<UserRoleRelationMapper, UserRoleRelation> implements IUserRoleRelationService {

    @Resource
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    @Transactional
    public boolean updateUserRoleRelation(int userId, List<Integer> roleIds) {
        deleteByUserId(userId);//删掉该用户下的角色关系

        roleIds.forEach( roleId -> {
            UserRoleRelation userRoleRelation = new UserRoleRelation();
            userRoleRelation.setRoleId(roleId);
            userRoleRelation.setUserId(userId);
            userRoleRelationMapper.insert(userRoleRelation);
        });
        return true;
    }

    private void deleteByUserId(int userId){
        LambdaQueryWrapper<UserRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRoleRelation::getUserId, userId);
        userRoleRelationMapper.delete(queryWrapper);
    }

}
